﻿using Forum.BaseController;
using Forum.Infrastructure.Util;
using Forum.Model.Dto;
using Forum.Model.Entity.System;
using Forum.Service.Interface;
using Microsoft.AspNetCore.Authorization;

namespace Forum.Controllers
{
    /// <summary>
    /// 用户信息
    /// </summary>
    [Route("Api/[controller]")]
    public class UserController : BaseController<IUserInfoService>
    {
        public UserController(IUserInfoService defaultService, ILogger<BaseController<IUserInfoService>> logger) : base(defaultService, logger)
        {
        }

        [HttpGet]
        public ApiResponsePaged<SYS_USER> GetList([FromQuery] UserQueryParameters param)
        {
            var pagedList = DefaultService.GetPagedList(param);
            return new ApiResponsePaged<SYS_USER>
            {
                msg = "Get User list",
                data = pagedList.ToList(),
                total = pagedList.Total,
                haveMore = pagedList.Total > param.Page * param.PageSize
            };
        }

        /// <summary>
        /// 批量新增用户（需完善）
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost("AddUsers")]
        public async Task<int> AddUsers(List<UserInfoReq> req)
        {
            return await DefaultService.AddUsers(req);
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResponse AddUser(UserInfoReq req)
        {
            DefaultService.AddUser(req);
            return ApiResponse.OK();
        }

        [AllowAnonymous]
        [HttpGet("{userId}")]
        public ApiResponse GetUserById(string userId)
        {
            var user = DefaultService.GetUser(userId);
            return ApiResponse.OK("", user);
        }

        /// <summary>
        /// 测试添加照片
        /// </summary>
        /// <param name="Files"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ApiResponse AddAvatar([FromForm] IFormCollection Files)
        {
            string dd = Files["File"];
            var form = Files;//定义接收类型的参数
            //Hashtable hash = new Hashtable();
            IFormFileCollection cols = Request.Form.Files;
            if (cols == null || cols.Count == 0)
            {
                return ApiResponse.OK();
            }
            foreach (IFormFile file in cols)
            {
                //var filename = "";
                //var fileTypes = ".gif,.jpg,.jpeg,.png,.bmp,.GIF,.JPG,.JPEG,.PNG,.BMP";
                //if (file.Length <= 10485760)//检查文件大小
                //{
                //    var suffix = Path.GetExtension(file.FileName);//提取上传的文件文件后缀
                //    var id = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();
                //    filename = $"{id.Substring(id.Length - 4, id.Length)}{suffix}";
                //    if (fileTypes.IndexOf(suffix) >= 0)//检查文件格式
                //    {
                //        using (FileStream fs = System.IO.File.Create($@"{Appsettings.App("FileBaseUrl")}\{filename}"))//注意路径里面最好不要有中文
                //        {
                //            file.CopyTo(fs);//将上传的文件文件流，复制到fs中
                //            fs.Flush();//清空文件流
                //        }
                //    }
                //}

            }
            var currentDate = DateTime.Now;
            var webRootPath = Appsettings.App("FileBaseUrl");

            //var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名
            //var fileSize = formFile.Length;
            //var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";
            ////保存的文件名称(以名称和保存时间命名)
            //var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

            ////文件保存
            //using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
            //{
            //    formFile.CopyTo(fs);
            //    fs.Flush();
            //}

            //完整的文件路径
            //var completeFilePath = Path.Combine(filePath, saveName);


            return ApiResponse.OK();
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ApiResponse UpdatePwd(PwdReq req)
        {
            try
            {
                var result = DefaultService.UpdatePwd(req);
                return result ? ApiResponse.OK() : ApiResponse.Error("更新失败！");
            }
            catch (Exception ex)
            {
                return ApiResponse.Error($"更新失败！{ex.Message}");
            }
        }

        [HttpPost("[action]")]
        public ApiResponse UploadAvatar(IFormFile file)
        {
            var imgUrl = DefaultService.UploadAvatar(file);
            return ApiResponse.OK("", new
            {
                imgUrl,
                imgName = Path.GetFileNameWithoutExtension(imgUrl)
            });
        }

    }
}
